#-------------------------------------------------------------------------------
# Name:        odp_png_converter.py
# Purpose:     Classes to convert ODP presentation files to the slidespeech internal 
#              data structure
#       
# Authors:      Glenn Ramsey <glenn.ramsey@slidespeech.com>
#
# Copyright:   (c) Slidespeech Ltd 2012
# Licence:     MIT license
#-------------------------------------------------------------------------------

import os
import glob

from converter import Converter, ConverterError
import odp2png

class ODPPngConverter(Converter):
    def __init__(self, odpFileName, previous=None):
        Converter.__init__(self, previous)    
        self._odpFileName = odpFileName
    
    def _convertImpl(self):

        self._imageDir = os.path.join(self.tempDir(), "images")
        try:
            os.makedirs(self._imageDir)
        except OSError:
            # dir already exists, shouldn't happen
            pass

        args = [self._odpFileName]
        odp2png.runparseNoOpts(args, tempDir=self._imageDir)

        # shouldn't be any need to check for an upper case extension
        self._slideList = sorted(glob.glob(os.path.join(self._imageDir, "*.png")))
                
        # add the image file locations to the script
        try:
            seq = self.script()['S']

            # check that we have the same number of images as notes
            if len(self._slideList) != len(seq):
                e = Exception("Number of images and slides is different")
                raise e
            
            for index, slide in enumerate(seq):
                slide['i'] = self._slideList[index]
            
        except KeyError as e:
            ex = ConverterError("Field missing in slide script", e)
            raise ex
        
    def slideList(self):
        return self._slideList
    
